package com.chenailin.www.service;

import com.chenailin.www.dao.DoctorDAO;
import com.chenailin.www.daoimpl.DoctorDAOImpl;
import com.chenailin.www.exception.ServiceException;
import com.chenailin.www.pojo.Department;
import com.chenailin.www.dao.DepartmentDAO;
import com.chenailin.www.daoimpl.DepartmentDAOImpl;

import java.sql.SQLException;
import java.util.List;

public class DepartmentService {
    private final DepartmentDAO departmentDAO = new DepartmentDAOImpl();
    private final DoctorDAO doctorDAO = new DoctorDAOImpl();

    // 添加科室
    public boolean addDepartment(Department department) throws IllegalArgumentException {
        if (departmentDAO.existByName(department.getDepartName())) {
            throw new IllegalArgumentException("科室名称已存在");
        }
        try {
            return departmentDAO.addDepartment(department) > 0;
        } catch (SQLException e) { // 明确捕获SQL异常
            throw new ServiceException("添加科室失败", e);
        }
    }

    // 删除科室
    public boolean deleteDepartment(int departId) throws IllegalArgumentException {
        // 检查科室下是否有医生
        if (doctorDAO.countByDepartment(departId)) {
            throw new IllegalStateException("科室下存在医生，无法删除");
        }
        try {
            return departmentDAO.deleteDepartment(departId);
        } catch (SQLException e) { // 明确捕获SQL异常
            throw new ServiceException("删除科室失败", e);
        }
    }

    // 修改科室
    public boolean modifyDepartment(Department department) {
        validateDepartment(department);
        try {
            if(!departmentDAO.modifyDepartment(department)) return false;
            departmentDAO.modifyDepartment(department);
            return true;
        } catch (SQLException e) { // 明确捕获SQL异常
            throw new ServiceException("修改科室失败", e);
        }
    }

    // 查看所有科室
    public List<Department> getAllDepartments() {
        return departmentDAO.getAllDepartments();
    }

    // 查看科室详情
    public Department getDepartmentDetail(int departId) {
        return departmentDAO.findById(departId);
    }

    // 是否为有效科室
    public boolean isValidDepartment(int departmentId) {
        return departmentDAO.findById(departmentId) != null;
    }

    // 是否为有效科室
    private void validateDepartment(Department department) throws IllegalArgumentException {
        if(department.getDepartName() == null || department.getDepartName().trim().isEmpty()) {
            throw new IllegalArgumentException("科室姓名不能为空");
        }
    }
}
